//
//  BBAlertManger.m
//  AlertManager
//
//  Created by aron on 2020/8/2.
//  Copyright © 2020 aron. All rights reserved.
//

#import "BBAlertManger.h"
#import "BBAlertModel.h"

@interface BBAlertManger ()

@property (nonatomic, assign) BOOL isExecuting;

@property (nonatomic, strong) NSMutableArray<BBAlertModel *> *alertExcuteQueue;

@end

@implementation BBAlertManger

+ (instancetype)sharedManager {
    static BBAlertManger *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [BBAlertManger new];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _isExecuting = NO;
    }
    return self;
}

- (void)executeAlertWithModel:(BBAlertModel *)alertModel {
    [self.alertExcuteQueue addObject:alertModel];

    if (self.isExecuting) {
        return;
    }

    [self doExecute];
}

- (void)doExecute {
    self.isExecuting = YES;
    if (self.alertExcuteQueue.count == 0) {
        self.isExecuting = NO;
        return;
    }
    [self.alertExcuteQueue sortUsingComparator:^NSComparisonResult(BBAlertModel *_Nonnull obj1, BBAlertModel *_Nonnull obj2) {
        return obj1.level < obj2.level;
    }];
    BBAlertModel *alertModel = self.alertExcuteQueue.firstObject;
    // 执行Block
    alertModel.executeBlock(alertModel);
    // 设置关闭Block
    __weak __typeof(self) weakSelf = self;
    __weak __typeof(alertModel) weakAlertModel = alertModel;
    alertModel.closeBlock = ^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        __strong __typeof(weakAlertModel) strongAlertModel = weakAlertModel;
        // 删除当前，执行下一个
        [strongSelf.alertExcuteQueue removeObject:strongAlertModel];

        // 执行下一个
        [strongSelf doExecute];
    };
}

- (NSMutableArray *)alertExcuteQueue {
    if (!_alertExcuteQueue) {
        _alertExcuteQueue = [NSMutableArray new];
    }
    return _alertExcuteQueue;
}

@end
